package learn.io.netty.demo.demo1;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.AttributeKey;

public class Server {

    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    // 设置服务器ServerSocketChannel
                    .channel(NioServerSocketChannel.class)
                    // 给每个客户端连接设置tcp属性
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    // 创建客户端连接的时候绑定一些基本属性
                    .childAttr(AttributeKey.newInstance("childAttr"), "childAttrValue")
                    // 加入服务端启动的逻辑
                    .handler(new ServerHandler())
                    // 客户端逻辑
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ServerHandler());
                            ch.pipeline().addLast(new ChannelOutboundHandlerAdapter());
                        }
                    });

            ChannelFuture f = b.bind(8888).sync();

            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
